package com.locust.upms.authc.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.locust.base.common.exception.AuthorizationException;
import com.locust.base.common.utils.IpHelper;
import com.locust.base.common.utils.date.DateUtil;
import com.locust.sso.common.pojo.SSOUser;
import com.locust.sso.common.tools.UserHolder;
import com.locust.upms.authc.annotaion.RequiresPermissions;

/**
 * 权限验证拦截器
 * 
 * @author yhaoquan
 * 
 */
public class AuthorizationInterceptorAdapter extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(AuthorizationInterceptorAdapter.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		RequiresPermissions permissions = handlerMethod.getMethodAnnotation(RequiresPermissions.class);

		boolean isPermissioin = false;

		if (null != permissions) {// 权限验证
			//当前登录用户信息
			SSOUser user = UserHolder.getUser();

			// 超级管理员，直接通过
			if (null != user && null != user.getIsAdmin() && user.getIsAdmin()) {
				return true;
			}

			// 鉴权
			if (user.getPermissions().contains(permissions.value())) {
				isPermissioin = true;
			}

		} else {// 没有权限注解，不需验证权限，直接通过
			return true;
		}

		if (isPermissioin) { // 鉴权通过
			return true;
		} else { // 鉴权不通过
			logger.info("验证权限==》不通过, 用户：{}, IP：{}, 方法：{}, 操作描述：{}, 权限：{}, 时间：{}", UserHolder.getRealName(), IpHelper.getIpAddr(request), handlerMethod.getMethod().getDeclaringClass().getCanonicalName() + "." + method.getName(), permissions.description(), permissions.value(), DateUtil.getDateTime());
			throw new AuthorizationException("权限不足，操作描述["+permissions.description()+"]，权限[" + permissions.value() + "]");
		}
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		super.afterConcurrentHandlingStarted(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}


}
